package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //1.添加管理员
    @PostMapping("add")
    public Result add(@RequestBody Admin admin){
        boolean b =adminService.add(admin);
        if (b){
            return new Result(true,StatusCode.OK,"添加管理员成功");
        }
        return new Result(false,StatusCode.ERROR,"添加管理员失败");
    }
    //2. 管理员登陆
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        //2.1 根据用户名查询用户是否存在，存在就比较密码是否相等
        Admin admin1 = adminService.login(admin);
        if (admin1 != null){
            //2.2 登陆成功后，用户信息写入token
            String token = jwtUtil.createJWT(admin1.getId(),admin1.getLoginname(),"admin");
            if (StringUtils.isNotBlank(token)){
                Map<String,String> map = new HashMap<>();
                map.put("token",token);
                map.put("loginname",admin1.getLoginname());
                return new Result(true,StatusCode.OK,"管理员登陆成功",map);
            }
        }
        return new Result(false,StatusCode.ERROR,"管理员登陆失败");
    }
    //3. 删除管理员
    @DeleteMapping("{adminId}")
    public Result dele(@PathVariable String adminId){
        //3.1 先从reqquest中得到claims
        Claims claims  = (Claims) request.getAttribute("claims");
        System.out.println("claims " + claims);
        //3.2 判断claims是否存在
        if (claims != null){
         //3.3 得到roles
         String roles = (String) claims.get("roles");
            System.out.println( "roles" + roles);
         if (StringUtils.isNotBlank(roles) && roles.equals("admin")){
             adminService.dele(adminId);
             return new Result(true,StatusCode.OK,"删除管理员成功");
         }

        }
        return new Result(false,StatusCode.ERROR,"权限不足");

    }
}
